package com.example.myapplication.loginandregister;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.database.entity.UserEntity;
import com.example.myapplication.MainActivity;
import com.example.myapplication.Myapplication;
import com.example.myapplication.R;
import com.example.myapplication.databinding.ActivityLoginBinding;
import com.mob.MobSDK;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends AppCompatActivity {
    private ActivityLoginBinding binding;

    String APPKEY = "324fe44a3c900";
    String APPSECRETE = "d94d6e3819e37a668fff3e531b87f5ca";

    // 倒计时
    int i = 30;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_login);
        init();
        cliclk();
        initListener();
    }

    private void init() {
        // 启动短信验证sdk
        MobSDK.init(this, APPKEY, APPSECRETE);
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                binding.textView29.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                binding.textView29.setText("获取验证码");
                binding.imageView29.setClickable(true);
                i = 30;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                        Toast.makeText(LoginActivity.this, "登录成功",
                                Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
                        LoginActivity.this.finish();
                    }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(LoginActivity.this, "正在获取验证码",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }else {
                    Toast.makeText(LoginActivity.this, "验证码错误",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    // 设置监听器
    private void initListener() {
        binding.editText2.addTextChangedListener(textWatcher);
        binding.editText3.addTextChangedListener(textWatcher);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            // 手机号输入框有内容时，叉号显示，否则隐藏
            if (binding.editText2.getEditableText().length() >= 1) {
                binding.deletephotonum.setVisibility(View.VISIBLE);
            }else {
                binding.deletephotonum.setVisibility(View.GONE);
            }

            if (binding.editText3.getEditableText().length() >= 1) {
                binding.imageView30.setVisibility(View.VISIBLE);
            }else {
                binding.imageView30.setVisibility(View.GONE);
            }
        }
    };

    private void cliclk() {

        // 返回主页面
        binding.returnmain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
            }
        });

        // 跳转到注册页面
        binding.gotoregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
            }
        });

        // 密码登录
        binding.imageView31.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,PassWordLoginActivity.class));
            }
        });
        binding.textView31.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,PassWordLoginActivity.class));
                LoginActivity.this.finish();
            }
        });

        // 点击将输入框清空
        binding.deletephotonum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.editText2.setText("");
            }
        });
        binding.imageView30.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.editText3.setText("");
            }
        });

        //登录
        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //获取输入的手机号码
                String phoneNumbers = binding.editText2.getText().toString();

                if (binding.editText2.getEditableText().length() == 0) {
                    Toast.makeText(LoginActivity.this, "手机号码不能为空", Toast.LENGTH_LONG).show();
                }else if (binding.editText3.getEditableText().length() == 0) {
                    Toast.makeText(LoginActivity.this, "验证码不能为空", Toast.LENGTH_LONG).show();
                }else {
                    Observable.create(new ObservableOnSubscribe<Boolean>() {
                        @Override
                        public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                            UserEntity userEntity = Myapplication.getInstance().getDatabase().userDao().getUserByPhoneNum(phoneNumbers);
                            Log.d("userEntity",userEntity.toString());
                            if (userEntity != null) {
                                emitter.onNext(true);
                            }else {
                                emitter.onNext(false);
                            }
                        }
                    })
                    .observeOn(Schedulers.io())   //为上面代码分配io线程
                    .subscribeOn(AndroidSchedulers.mainThread())   //为下面的代码分配主线程
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean == true) {
                                //将收到的验证码和手机号提交再次核对
                                SMSSDK.submitVerificationCode("86", phoneNumbers, binding.editText3
                                        .getText().toString());
                            }else {
                                Toast.makeText(LoginActivity.this,"改用户未注册",Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            }
        });

        //获取验证码
        binding.imageView29.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //获取输入的手机号码
                String phoneNumbers = binding.editText2.getText().toString();

                //1,通过规则判断手机号
                if (!judgePhoneNums(phoneNumbers)) {
                    return;
                }
                //2,通过sdk发送短信验证
                SMSSDK.getVerificationCode("86",phoneNumbers);

                //3,把按钮变成不可点击，并且显示倒计时(正在获取)
                binding.imageView29.setClickable(false);
                binding.textView29.setText("重新发送(" + i + ")");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-9);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-8);
                    }
                }).start();
            }
        });
    }

    /**
     * 验证手机号码
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums,11)
                && isMobileNo(phoneNums)) {
            return true;
        }
        Toast.makeText(this,"手机号码输入有误！", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * 验证手机号码长度
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        }else {
            return str.length() == length ? true : false;
        }
    }

    /**
     * 验证是否是手机号码
     */
    public static boolean isMobileNo(String mobileNums) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
         * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums)) {
            return false;
        }else {
            return mobileNums.matches(telRegex);
        }
    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }
}